package com.knife.news.business;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.context.Context;
import org.apache.velocity.io.VelocityWriter;

import com.knife.bbs.business.BBSCoreService;
import com.knife.bbs.business.BBSDirService;
import com.knife.bbs.business.BBSUserService;
import com.knife.bbs.object.BBSDir;
import com.knife.bbs.object.BBSDoc;
import com.knife.bbs.object.UserInfo;
import com.knife.util.CommUtil;
import com.knife.util.HtmlUtil;
import com.knife.web.Globals;
import com.knife.web.RequestProcessor;
import com.knife.web.tools.CommTool;
import com.knife.web.tools.IPageList;

public class HTMLGenerater {
	private String fileName;
	private static String encoding = "utf-8";
	// private String baseDir="/html/";
	private static final Logger logger = (Logger) Logger
			.getLogger(RequestProcessor.class.getName());
	private static BBSDirService dirService = BBSDirService.getInstance();
	private static BBSCoreService coreService = BBSCoreService.getInstance();
	private static BBSUserService userService = BBSUserService.getInstance();

	public HTMLGenerater() {
	}

	public static boolean saveToHTML(BBSDoc obj) throws Exception {
		Context context = null;
		Template template = null;
		BBSDir dir = dirService.getBBSDirBySN(obj.getDirsn());
		context = new VelocityContext();
		if (dir != null)
			context.put("dir", dir);
		else
			context.put("msg", "目录不存在，可能是地址链接错误！");
		context.put("cid", obj.getCid());
		context.put("title", obj.getTitle());
		// System.out.println(obj.getContent());
		String content = HtmlUtil.getUBB2HTML(coreService
				.replaceEmotTag(HtmlUtil.escapeHTMLTag(obj.getContent())));
		context.put("content", content);
		context.put("inputuser", obj.getInputtime());
		context.put("modifytime", obj.getModifytime());
		if (obj.getTagpic() != null && !obj.getTagpic().equals(""))
			context.put("tagpic", obj.getTagpic());
		if (obj.getImgs() != null && !obj.getImgs().equals(""))
			context.put("imgs", obj.getImgs());
		context.put("files", obj.getFiles());
		context.put("ip", obj.getIp());
		context.put("username", obj.getInputuser());
		context.put("encodUserName",
				URLEncoder.encode(obj.getInputuser(), "utf-8"));
		// 取得发帖人的相关信息
		 UserInfo inputUser=userService.getUserInfoByName(obj.getInputuser());
		 if(inputUser!=null) {
			 context.put("topicUser",inputUser);
		 }
		int pageSize = 100;
		int currentPage = 1;
		IPageList pList = coreService.queryReply(obj, pageSize, currentPage);
		List replyList = new ArrayList();
		if (pList != null) {
			List list = pList.getResult();
			if (list != null) {
				for (int i = 0; i < list.size(); i++) {
					Map map = new HashMap();
					BBSDoc reply = (BBSDoc) list.get(i);
					map.put("cid", reply.getCid());
					map.put("title", reply.getTitle());
					map.put("content", HtmlUtil.getUBB2HTML(coreService
							.replaceEmotTag(HtmlUtil.escapeHTMLTag(reply
									.getContent()))));
					map.put("inputtime", reply.getInputtime());
					map.put("modifytime", reply.getModifytime());
					map.put("ip", reply.getIp());
					map.put("imgs", reply.getImgs() == null ? null
							: ((Object) (reply.getImgs().equals("") ? null
									: ((Object) (reply.getImgs())))));
					map.put("files", reply.getFiles());
					if (reply.getTagpic() != null
							&& !reply.getTagpic().equals(""))
						map.put("tagpic", reply.getTagpic());
					map.put("floor", new Integer(pageSize * (currentPage - 1)
							+ i + 1));
					map.put("username", reply.getInputuser());
					map.put("encodUserName",
							URLEncoder.encode(reply.getInputuser(), "utf-8"));
					UserInfo replyUser=userService.getUserInfoByName(obj.getInputuser());
					 if(inputUser!=null) {
						 map.put("replyUser",replyUser);
					 }
					replyList.add(map);
				}

			}
			context.put("list", replyList);
			context.put("pages", new Integer(pList.getPages()));
			context.put("rows", new Integer(pList.getRowCount()));
			context.put(
					"gotoPageHTML",
					CommUtil.showPageHtml(pList.getCurrentPage(),
							pList.getPages()));
			context.put("page", new Integer(currentPage));
		}
		CommTool.createUtilContext(context);
		String fileName = obj.staticHtmlUrl();
		File file = new File(Globals.APP_BASE_DIR + "/" + fileName);
		if (!file.getParentFile().exists())
			file.getParentFile().mkdirs();
		String templateName = "/bbs/bbsAppShow.html";
		template = VelocityFactory.getTemplate(templateName, "utf-8");
		mergeTemplate(template, context, file);
		return true;
	}

	protected static void mergeTemplate(Template template, Context context,
			File file) {
		Writer writer = null;
		VelocityWriter vw = null;
		try {
			writer = new OutputStreamWriter(new FileOutputStream(file),
					template.getEncoding());
			vw = new VelocityWriter(writer, 4 * 1024, true);
			template.merge(context, vw);
		} catch (Exception e) {
			logger.error("合成错误：" + e);
			e.printStackTrace();
		} finally {
			if (vw != null) {
				try {
					vw.flush();
					vw.close();
					writer.close();
				} catch (Exception e) {
					logger.error(e.getMessage());
					e.printStackTrace();
				}
			}
		}
	}
}
